﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace FileArchive
{
    public partial class ArchiveForm : Form
    {
        public ArchiveForm()
        {
            InitializeComponent();
            docView.PathChanged += docView_PathChanged;
        }

        void docView_PathChanged(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = docView.Path.Count - 1; i >= 0; i--)
            {
                sb.Append(docView.Path[i].Name);
                if (i > 0)
                    sb.Append("\\");
            }
            pathLabel.Text = sb.ToString();
        }

        internal Archive Archive { get { return docView.Archive; } set { docView.Archive = value; Text = "Archive - " + value.Root.Name; } }

        private void ArchiveForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            docView.Dispose();
            this.Archive.Dispose();
        }

        private void gotoParentFolderButton_Click(object sender, EventArgs e)
        {
            if (docView.CurrentDirectory != null && docView.CurrentDirectory.Parent != null)
                docView.CurrentDirectory = docView.CurrentDirectory.Parent;
        }

        private void thumbSizeTrack_Scroll(object sender, EventArgs e)
        {
            docView.ThumbSize = thumbSizeTrack.Value;
            docView.Invalidate();
        }

        private void docView_FileItemDoubleClick(object sender, EventArgs e)
        {
            var fileNode = docView.CurrentDirectory.Children[docView.SelectedIndex];
            if (ImageExtensions.Contains(Path.GetExtension(fileNode.Name).ToLower()))
            {
                var form = new DocumentForm();
                form.Archive = Archive;
                form.Folder = docView.Path[0];
                form.DocumentPosition = docView.SelectedIndex;
                form.Show();
            }
            else
            {
                var fileName = Path.GetTempFileName() + Path.GetExtension(fileNode.Name);
                using (var stream = Archive.LoadFile(fileNode as FileNode))
                {
                    using (var fs = new FileStream(fileName, FileMode.Create))
                    {
                        stream.CopyTo(fs);
                    }
                }
                Process proc = new Process();
                proc.StartInfo = new ProcessStartInfo(fileName);
                proc.StartInfo.UseShellExecute = true;
                proc.EnableRaisingEvents = true;
                proc.Exited += (obj, args) => { try { File.Delete(fileName); } catch (Exception) { } };
                proc.Start();
            }
        }
    }
}
